import {
  getNewCartGoods,
  mergeLocalCart,
  findCartList,
  insertCart,
  deleteCart,
  updateCart,
  checkAllCart,
} from "api/cart.js";

export default {
  namespaced: true,
  state() {
    return {
      // 购物车商品列表
      list: [],
    };
  },

  mutations: {
    insertCart(state, payload) {
      //判断是否有相同
      //如果有相同：查询数量，累加payload，删除原来，添加到最新位置
      //没有相同，直接保存
      //这里查找用findIndex，找不到返回-1；如果用find，找不到返回undefined
      const sameIndex = state.list.findIndex(
        (goods) => goods.skuId === payload.skuId
      );
      if (sameIndex > -1) {
        const count = state.list[sameIndex].count;
        //添加多少件
        payload.count += count;
        state.list.splice(sameIndex, 1);
      }
      state.list.unshift(payload);
    },
    //修改购物车
    updateCart(state, payload) {
      //判断是否有效、有库存、是否变价
      const updateGoods = state.list.find(
        (item) => item.skuId === payload.skuId
      );
      for (const key in payload) {
        if (
          //字段合理验证,由于传入的数据类型不同，有boolean，有字符串等，所以要多个限制条件
          payload[key] !== undefined &&
          payload[key] !== null &&
          payload[key] !== ""
        ) {
          updateGoods[key] = payload[key];
        }
      }
    },
    deleteCart(state, skuId) {
      const index = state.list.findIndex((item) => item.skuId === skuId);
      state.list.splice(index, 1);
    },
    //设置
    setCart(state, payload) {
      //当payload为空，则为清空
      state.list = payload;
      //若有值，则为设置
    },
  },

  actions: {
    //插入
    insertCart(ctx, sku) {
      //同步异步
      return new Promise((res, rej) => {
        //已经登录;ctx.rootState根下的同store
        if (ctx.rootState.user.profile.token) {
          insertCart({ skuId: sku.skuId, count: sku.count })
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              ctx.commit("setCart", data.result);
              res();
            });
        } else {
          //未登录
          ctx.commit("insertCart", sku);
          //代表执行成功，否者没有信息返回
          res();
        }
      });
    },
    //获取商品列表
    findCart(ctx, payload) {
      return new Promise((res, rej) => {
        //登录
        if (ctx.rootState.user.profile.token) {
          findCartList().then((data) => {
            ctx.commit("setCart", data.result);
            // console.log(data.result);
            res();
          });
        } else {
          //本地
          //同时发请求，所有请求成功再一次修改本地数据promise.all
          const promiseArr = ctx.state.list.map((goods) => {
            return getNewCartGoods(goods.skuId);
          });
          Promise.all(promiseArr).then((result) => {
            //更新购物车
            result.forEach((dataList, i) => {
              ctx.commit("updateCart", {
                //根据索引一个个更新
                skuId: ctx.state.list[i].skuId,
                ...dataList.result,
              });
            });
          });
          //成功
          res();
        }
      });
    },
    //删除
    deleteCart(ctx, skuId) {
      //同步异步
      return new Promise((res, rej) => {
        //已经登录;ctx.rootState根下的同store
        if (ctx.rootState.user.profile.token) {
          deleteCart([skuId])
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              ctx.commit("setCart", data.result);
              res();
            });
        } else {
          //未登录
          ctx.commit("deleteCart", skuId);
          //代表执行成功，否者没有信息返回
          res();
        }
      });
    },
    //修改购物车（选择、数量）
    updateCart(ctx, payload) {
      //payload内容：必有skuId，可能有：selected、count等
      //同步异步
      return new Promise((res, rej) => {
        //已经登录;ctx.rootState根下的同store
        if (ctx.rootState.user.profile.token) {
          updateCart(payload)
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              ctx.commit("setCart", data.result);
              res();
            });
        } else {
          //未登录
          ctx.commit("updateCart", payload);
          //代表执行成功，否者没有信息返回
          res();
        }
      });
    },
    //全选状态
    checkAll(ctx, selected) {
      //同步异步
      return new Promise((res, rej) => {
        //已经登录;ctx.rootState根下的同store
        if (ctx.rootState.user.profile.token) {
          const ids = ctx.getters.validList.map((item) => item.skuId);
          checkAllCart({ selected, ids })
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              ctx.commit("setCart", data.result);
              res();
            });
        } else {
          //未登录
          ctx.getters.validList.forEach((goods) => {
            ctx.commit("updateCart", { skuId: goods.skuId, selected });
          });
          //代表执行成功，否者没有信息返回
          res();
        }
      });
    },
    //批量删除
    batchDeleteCart(ctx, isClear) {
      //同步异步
      return new Promise((res, rej) => {
        //已经登录;ctx.rootState根下的同store
        if (ctx.rootState.user.profile.token) {
          const ids = ctx.getters[isClear ? "invalidList" : "selectedList"].map(
            (item) => item.skuId
          );
          deleteCart(ids)
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              ctx.commit("setCart", data.result);
              res();
            });
        } else {
          //未登录
          ctx.getters[isClear ? "invalidList" : "selectedList"].forEach(
            (item) => {
              ctx.commit("deleteCart", item.skuId);
            }
          );
          //代表执行成功，否者没有信息返回
          res();
        }
      });
    },
    //规格改变
    changeCartSku(ctx, { oldSkuId, newSku }) {
      //同步异步
      return new Promise((res, rej) => {
        //已经登录;ctx.rootState根下的同store
        if (ctx.rootState.user.profile.token) {
          const oldGoods = ctx.state.list.find(
            (item) => item.skuId === oldSkuId
          );
          deleteCart([oldGoods.skuId])
            .then(() => {
              //再返回一个promise
              return insertCart({ skuId: newSku.skuId, count: oldGoods.count });
            })
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              ctx.commit("setCart", data.result);
              res();
            });
          //只需要传数量和skuid即可
          ctx.commit("insertCart", newGoods);
          res();
        } else {
          //未登录
          const oldGoods = ctx.state.list.find(
            (item) => item.skuId === oldSkuId
          );
          ctx.commit("deleteCart", oldSkuId);
          const {
            skuId,
            price: nowPrice,
            specsText: attrsText,
            inventory: stock,
          } = newSku;

          //新旧合并
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, stock };
          ctx.commit("insertCart", newGoods);
          res();
        }
      });
    },
    //合并购物车
    async mergeCart(ctx) {
      const cartList = ctx.state.list.map((item) => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count,
        };
      });
      await mergeLocalCart(cartList);
      //到此处，合并完成，如果网络请求错误则直接报错
      ctx.commit("setCart", []);
    },
  },

  getters: {
    //列表，展示有效商品，有效标识符 && 库存
    validList(state) {
      return state.list.filter((goods) => goods.stock > 0 && goods.isEffective);
    },
    //总件数
    validTotal(state, getters) {
      return getters.validList.reduce((p, c) => {
        return p + c.count;
      }, 0);
    },
    //总金额
    validPrice(state, getters) {
      return (
        getters.validList.reduce((p, c) => {
          //去除浮点
          return p + c.count * c.nowPrice * 100;
        }, 0) / 100
      );
    },
    //购物车内容数据处理都在Vuex内处理完毕
    //无效商品列表
    invalidList(state) {
      return state.list.filter(
        (goods) => goods.stock <= 0 || !goods.isEffective
      );
    },
    //已选商品列表,selective
    selectedList(state, getters) {
      return getters.validList.filter((item) => item.selected);
    },
    //已选商品总件数
    selectedTotal(state, getters) {
      return getters.selectedList.reduce((p, c) => {
        return p + c.count;
      }, 0);
    },
    //已选商品总金额
    selectedPrice(state, getters) {
      return (
        getters.selectedList.reduce((p, c) => {
          //去除浮点
          return p + c.count * c.nowPrice * 100;
        }, 0) / 100
      );
    },
    //是否全选
    isCheckAll(state, getters) {
      //我这用的every，感觉更清楚些
      return (
        getters.validList.every((item) => item.selected) &&
        getters.validList.length != 0
      );
    },
  },
};
